# -*- coding: utf-8 -*-

import time
import logging
import hmac
import hashlib
import base64
import requests
import json
from datetime import datetime


def nowTime():
    now = datetime.now()
    # 将时间格式化为字符串
    formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
    return formatted_time


# 发送钉钉通知的函数
def send_dingtalk_alert(message):
    # 设置 Webhook 地址
    url = "https://oapi.dingtalk.com/robot/send?access_token=c54fa6837d584b0abc56c0a7d0456ca37d59213dcc7ea3f6f104b20de3c71284"
    secret = "SEC9de9f15e7d9bc3be3c0c5f50adcf283ff26189940919486b9cdb0feda9ee45b1"

    # 获取当前时间戳（毫秒级）
    timestamp = str(int(time.time() * 1000))

    # 构建签名字符串
    string_to_sign = "{}\n{}".format(timestamp, secret)

    # 计算签名值
    signature = base64.b64encode(
        hmac.new(
            secret.encode("utf-8"), string_to_sign.encode("utf-8"), hashlib.sha256
        ).digest()
    ).decode("utf-8")

    # 构建请求头
    headers = {
        "Content-Type": "application/json",
        "Charset": "UTF-8",
        "timestamp": timestamp,
        "sign": signature,
    }

    data = {"msgtype": "text", "text": {"content": message}}

    try:
        response = requests.post(url, data=json.dumps(data), headers=headers)
        print(data)
        print(response)
        if response.status_code == 200:
            print("钉钉通知发送成功！")
    except Exception as e:
        error_message = "发送钉钉通知时发生异常：{}".format(e)
        print(error_message)
        logging.error(error_message)
        print("钉钉通知发送失败，HTTP 状态码：", response.status_code)


current_time = nowTime()
access_message = "*{}，测试一下。*".format(current_time)
send_dingtalk_alert(access_message)

